package com.googlecode.garbagecan.test.socket.sample5;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class MyClient {
	
	private final static Logger logger = Logger.getLogger(MyClient.class.getName());

	private final static String host = "localhost";
	private final static int port = 10000;
	
	public static void main(String[] args) throws Exception {
		if (args.length == 0) {
			return;
		}
		if (args[0].equals("0")) {
			test(false);
		} else if (args[0].equals("1")) {
			test(true);
		} else {
			testStreamSize(false);
			testStreamSize(true);
			return;
		}
	}
	
	public static void testStreamSize(boolean compress) throws Exception {
		long start = System.currentTimeMillis();
		Socket socket = new Socket();
		SocketAddress socketAddress = new InetSocketAddress(host, port); 
		socket.connect(socketAddress, 10 * 1000);
		BigObject bo = new BigObject("my big object ", 1024 * 1024 * 10);
		ObjectOutputStream oos = null;
		GZIPOutputStream gzipos = null;
		if (compress) {
			gzipos = new GZIPOutputStream(socket.getOutputStream());
			oos = new ObjectOutputStream(gzipos);
		} else {
			oos = new ObjectOutputStream(socket.getOutputStream());
		}
		oos.writeObject(bo);
		oos.flush();
		if (compress) {
			gzipos.finish();
		}
		oos.close();
		socket.close();
		long stop = System.currentTimeMillis();
		logger.log(Level.INFO, "Time: " + (stop - start));
	}
	
	public static void test(boolean compress) throws Exception {
		for (int i = 0; i < 100; i++) {
			long start = System.currentTimeMillis();
			Socket socket = new Socket();
			SocketAddress socketAddress = new InetSocketAddress(host, port); 
			socket.connect(socketAddress, 10 * 1000);
			
			BigObject bo = new BigObject("my big object " + i, 1024 * 1024 * 10);
			
			// Send object
			ObjectOutputStream oos = null;
			GZIPOutputStream gzipos = null;
			if (compress) {
				gzipos = new GZIPOutputStream(socket.getOutputStream());
				oos = new ObjectOutputStream(gzipos);
			} else {
				oos = new ObjectOutputStream(socket.getOutputStream());
			}
			oos.writeObject(bo);
			oos.flush();
			if (compress) {
				gzipos.finish();
			}
			
			// Receive object
			GZIPInputStream gzipis = null;
			ObjectInputStream ois = null;
			if (compress) {
				gzipis = new GZIPInputStream(socket.getInputStream());
				ois = new ObjectInputStream(gzipis);
			} else {
				ois = new ObjectInputStream(socket.getInputStream());
			}
			Object obj = ois.readObject();
			logger.log(Level.INFO, obj.toString());
			
			ois.close();
			oos.close();
			socket.close();
			long stop = System.currentTimeMillis();
			logger.log(Level.INFO, "Time: " + (stop - start));
		}
	}
}
